/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ScenerioSettingsFrame.java
 *
 * Created on Sep 24, 2010, 4:05:38 AM
 */

package nsdh.view;

import nsdh.*;
import javax.swing.table.*;
import javax.swing.*;
import java.util.*;
import nsdh.model.script_models.*;
import javax.swing.event.*;


/**
 *
 * @author notroot
 */
public class ScenerioSettingsFrame extends javax.swing.JFrame {

    /** Creates new form ScenerioSettingsFrame */
    public ScenerioSettingsFrame(NsdhController nsdhController) {
        initComponents();

        this.nsdhController = nsdhController;
        createScenerioTableFields();
        this.setLocationRelativeTo(null);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        totalTimeLabel = new javax.swing.JLabel();
        totalTimeTextField = new javax.swing.JTextField();
        scenarioPanel = new javax.swing.JPanel();
        addButton = new javax.swing.JButton();
        removeButton = new javax.swing.JButton();
        scenarioScrollPane = new javax.swing.JScrollPane();
        scenarioTable = new javax.swing.JTable();
        okButton = new javax.swing.JButton();
        cancelButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Scenariusz Symulacji");
        setBounds(new java.awt.Rectangle(100, 50, 0, 0));
        setResizable(false);

        totalTimeLabel.setText("Czas calkowity symulacji[s]:");

        scenarioPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Scenariusz"));

        addButton.setText("Dodaj");
        addButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addButtonActionPerformed(evt);
            }
        });

        removeButton.setText("Usun");
        removeButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                removeButtonActionPerformed(evt);
            }
        });

        scenarioTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        scenarioScrollPane.setViewportView(scenarioTable);

        javax.swing.GroupLayout scenarioPanelLayout = new javax.swing.GroupLayout(scenarioPanel);
        scenarioPanel.setLayout(scenarioPanelLayout);
        scenarioPanelLayout.setHorizontalGroup(
            scenarioPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(scenarioPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(scenarioScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 455, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(scenarioPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(removeButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(addButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 82, Short.MAX_VALUE))
                .addContainerGap())
        );
        scenarioPanelLayout.setVerticalGroup(
            scenarioPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(scenarioPanelLayout.createSequentialGroup()
                .addGroup(scenarioPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(scenarioScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 250, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(scenarioPanelLayout.createSequentialGroup()
                        .addComponent(addButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(removeButton)))
                .addContainerGap())
        );

        okButton.setText("OK");
        okButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                okButtonActionPerformed(evt);
            }
        });

        cancelButton.setText("Anuluj");
        cancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(totalTimeLabel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(totalTimeTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 214, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(scenarioPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                .addContainerGap())
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(232, Short.MAX_VALUE)
                .addComponent(okButton, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(cancelButton, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(208, 208, 208))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(totalTimeLabel)
                    .addComponent(totalTimeTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(scenarioPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(okButton)
                    .addComponent(cancelButton))
                .addContainerGap(14, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okButtonActionPerformed
        // TODO add your handling code here:
        try{
            DefaultTableModel model = (DefaultTableModel)scenarioTable.getModel();
            if(scenarioTable.getCellEditor()!=null){
                scenarioTable.getCellEditor().stopCellEditing();
            }
            
            SaveScenarioToNsdhModel();
            this.dispose();
         }catch(Exception e){
            JOptionPane.showMessageDialog(this, e.getMessage(), "Ostrzeżenie", JOptionPane.WARNING_MESSAGE);
        }
        
    }//GEN-LAST:event_okButtonActionPerformed

    private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
       this.dispose();
    }//GEN-LAST:event_cancelButtonActionPerformed

    /**
     * Dodaje nowy pusty wiersz na koncu tabeli
     * @param evt
     */
    private void addButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addButtonActionPerformed

        DefaultTableModel model = (DefaultTableModel)scenarioTable.getModel();
        Object[] newRow = {"","","",""};
        
        if(scenarioTable.getSelectedRow()!=-1){ //wstaw pod zaznaczonym elementem

            model.insertRow(scenarioTable.getSelectedRow()+1, newRow);
            model.fireTableDataChanged();

            scenarioTable.requestFocusInWindow();

            
        }else{ //nie zaznaczony zaden element - dodaj na koncu

            if(scenarioTable.isEditing()){
                scenarioTable.editingStopped(new ChangeEvent(addButton));
            }
            model.fireTableDataChanged();
            model.insertRow(model.getRowCount(), newRow);
            model.fireTableDataChanged();
            scenarioTable.requestFocusInWindow();

        }
        

    }//GEN-LAST:event_addButtonActionPerformed

    private void removeButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_removeButtonActionPerformed
        // TODO add your handling code here:
        DefaultTableModel model = (DefaultTableModel)scenarioTable.getModel();

        int[] selectedRows = scenarioTable.getSelectedRows();
        java.util.Arrays.sort(selectedRows);
        for(int i=selectedRows.length-1; i>= 0; i--){

            if(scenarioTable.isEditing()){
                scenarioTable.editingStopped(new ChangeEvent(addButton));
            }
            model.fireTableDataChanged();
            model.removeRow(selectedRows[i]);
            model.fireTableDataChanged();
            scenarioTable.requestFocusInWindow();

        }
        
    }//GEN-LAST:event_removeButtonActionPerformed


    private void createScenerioTableFields(){

        //zainicjalizuj model tabeli
        String[] values = new String[]{"Czas [s]", "Polaczenie", "Operacja","Wartosc"};
        scenarioTable.setModel(new DefaultTableModel(values,0));
        DefaultTableModel model = (DefaultTableModel)scenarioTable.getModel();

        //ustawia szerokosc kolumny czas
        scenarioTable.getColumnModel().getColumn(0).setPreferredWidth(5);

        //tworzy mape nazwa wyswietlana w combobox -> server_client_connection name
        serverClientConnectionComboBoxMap = new HashMap<String,String>();
        for(Server_client_connection server_client_connection: nsdhController.nsdhModel.network_structure.server_client_connection_list.values()){
            String comboBoxLabel = server_client_connection.server_pc + " --> " + server_client_connection.client_pc + " [" + server_client_connection.service + "]";
            serverClientConnectionComboBoxMap.put(comboBoxLabel, server_client_connection.name);
        }


        Set<String> serverClientConnectionNameSet = new HashSet(serverClientConnectionComboBoxMap.keySet());
        serverClientConnectionNameSet.add("");
        Object[] serverClientConnectionNameArray = serverClientConnectionNameSet.toArray();
        java.util.Arrays.sort(serverClientConnectionNameArray);

        //inicjalizuje combobox server-client-connection
        JComboBox serverClientConnectionComboBox = new JComboBox(serverClientConnectionNameArray);

        //dodaje combox do tabeli
        scenarioTable.getColumnModel().getColumn(1).setCellEditor(new DefaultCellEditor(serverClientConnectionComboBox));
        
        //ustaw combobox dla kolumny operacja
        JComboBox operationComboBox = new JComboBox();
        operationComboBox.addItem("");
        operationComboBox.addItem("start");
        operationComboBox.addItem("stop");
        operationComboBox.addItem("produce");
        operationComboBox.addItem("producemore");
        operationComboBox.addItem("send");
        //ustaw combobox i szerokosc kolumny
        scenarioTable.getColumnModel().getColumn(2).setCellEditor(new DefaultCellEditor(operationComboBox));
        scenarioTable.getColumnModel().getColumn(2).setPreferredWidth(5);

        scenarioTable.getColumnModel().getColumn(3).setPreferredWidth(5);

        LoadScenarioFromNsdhModel();


        pack();
    }

    private void LoadScenarioFromNsdhModel(){

        //zaladuj total_time
        totalTimeTextField.setText(nsdhController.nsdhModel.scenario.total_time);

        DefaultTableModel model = (DefaultTableModel)scenarioTable.getModel();

        //wyczysc tabele
        int rowsNum = scenarioTable.getRowCount();
        for(int i=rowsNum-1; i>= 0; i--){
            model.removeRow(i);
        }

        //dodaj do tabeli wiersze z modelu
        for(Event event: nsdhController.nsdhModel.scenario.eventList){
            String[] eventArray = new String[4];
            eventArray[0]= event.time;

            //przetlumacz nazwe polaczenia do formatu PC1->PC2 [FTP]
            Iterator iter = serverClientConnectionComboBoxMap.entrySet().iterator();
            while(iter.hasNext()){
                Map.Entry entry = (Map.Entry)iter.next();
                if(entry.getValue().equals(event.server_client_connection)){
                    eventArray[1]=(String)entry.getKey();
                }
            }

            eventArray[2]= event.command;
            eventArray[3]= event.value;

            model.insertRow(model.getRowCount(), eventArray);
        }

    }

    private void SaveScenarioToNsdhModel() throws Exception{


        DefaultTableModel model = (DefaultTableModel)scenarioTable.getModel();

        //tymczasowa tabela ze zdarzeniami
        ArrayList<Event> tempEventList = new ArrayList<Event>();

        //dodaj wszystkie wiersze do tabeli ze zdarzeniami
        for(int i=0; i< model.getRowCount();i++){
            Event newEvent = new Event();

            //sprawdz czy czas to liczba
            try{
                Double.parseDouble((String)model.getValueAt(i, 0));
                newEvent.time=(String)model.getValueAt(i, 0);
            }
            catch(Exception e){
                throw new Exception("Pole czas musi byc liczba.");
            }

            //sprawdz czy znajduje sie na liscie server_client_connection
            String tempConnectionName = serverClientConnectionComboBoxMap.get((String)model.getValueAt(i, 1));
            if(tempConnectionName!=null && !tempConnectionName.equals("") && nsdhController.nsdhModel.network_structure.server_client_connection_list.containsKey(tempConnectionName)){
                newEvent.server_client_connection=tempConnectionName;
            }else{
                throw new Exception("Wybrane polaczenie nie znajduje sie na liscie");
            }
            
            //opracja
            String tempCommand = (String)model.getValueAt(i, 2);
            if(tempCommand.equals("")){
                throw new Exception("Nie wybrana operacja");
                
            }else if((tempCommand.equals("produce") || tempCommand.equals("producemore") || tempCommand.equals("send"))
                    && !nsdhController.nsdhModel.network_settings.service_list.get(nsdhController.nsdhModel.network_structure.
                    server_client_connection_list.get(tempConnectionName).service).server_application.type.contains("FTP"))
                {
                throw new Exception("Operacje produce, producemore, send sa tylko dla uslugi typu Application/FTP");
            }
            else{
                newEvent.command=(String)model.getValueAt(i, 2);
            }

            //wartosc
            if(tempCommand.equals("produce") || tempCommand.equals("producemore") || tempCommand.equals("send")){
                try{
                    Double.parseDouble((String)model.getValueAt(i, 3));
                    newEvent.value=(String)model.getValueAt(i, 3);
                }
                catch(Exception e){
                    throw new Exception("Pole wartosc dla operacji produce, producemore, send musi byc liczba.");
                }
            }else if((String)model.getValueAt(i, 3)!=null && !((String)model.getValueAt(i, 3)).equals("")){
                throw new Exception("Pole wartosc moze byc niepuste tylko dla operacji produce, producemore, send.");
            }else{
                newEvent.value="";
            }
            

            tempEventList.add(newEvent);
        }

        //zaladuj total_time
        try{
            Double.parseDouble(totalTimeTextField.getText());
            nsdhController.nsdhModel.scenario.total_time=totalTimeTextField.getText();
        }
        catch(Exception e){
            throw new Exception("Pole czas calkowity musi byc liczba.");
        }
        
        nsdhController.nsdhModel.scenario.eventList = tempEventList;

       

    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton addButton;
    private javax.swing.JButton cancelButton;
    private javax.swing.JButton okButton;
    private javax.swing.JButton removeButton;
    private javax.swing.JPanel scenarioPanel;
    private javax.swing.JScrollPane scenarioScrollPane;
    private javax.swing.JTable scenarioTable;
    private javax.swing.JLabel totalTimeLabel;
    private javax.swing.JTextField totalTimeTextField;
    // End of variables declaration//GEN-END:variables

    private  JTable scenerioTable;
    protected NsdhController nsdhController;
    protected HashMap<String,String> serverClientConnectionComboBoxMap;
}
